﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using Cfg.Exceptions;
using Cfg.ValidationAttributes;
using NUnit.Framework;

namespace Cfg.Test.Validators
{
    [TestFixture]
    public class CustomValidatorTest
    {
        public class MustBetXYorZAttribute : CfgFinalizedStringValueValidatorBaseAttribute
        {
            protected override void Validate(string finalizedStringValue)
            {
                if (!new[] {"X", "Y", "Z"}.Contains(finalizedStringValue))
                    throw new Exception("Must be x y or z");
            }
        }

        public interface ITestConfig
        {
            ICustomValidationSection Custom { get; }
        }

        public interface ICustomValidationSection
        {
            [MustBetXYorZ]
            string InvalidValue { get; }

            [MustBetXYorZ]
            string ValidValue { get; }
        }

        [Test]
        public void Test()
        {
            try
            {
                Cfg.AppSettings.Init<ITestConfig>();
            }
            catch (ConfigValidationException<ITestConfig> ex)
            {
                var cfg = AppSettings.Get<ITestConfig>();

                Assert.AreEqual(1, ex.ValidationErrors.Length);
                Assert.AreEqual("Custom.InvalidValue", ex.ValidationErrors[0].Key);

                // values which do not pass validation are not set
                Assert.AreEqual(null, cfg.Custom.InvalidValue);

                // other values can still be fetched
                Assert.AreEqual("X", cfg.Custom.ValidValue);
            }

        }
    }
}